package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.SetmealDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    //新增套餐
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithSetmeal(setmealDto);
        redisTemplate.delete("setmeal_*");
        return R.success("保存成功");
    }

    //套餐分页查询
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    public R<Page<SetmealDto>> setmealPage(Integer page,Integer pageSize,String name){
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Setmeal::getName,name);
        lqw.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pageInfo,lqw);
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);
            String categoryId = setmealDto.getCategoryId();
            Category category = categoryService.getById(categoryId);
            String name1 = category.getName();
            setmealDto.setCategoryName(name1);
            //BeanUtils.copyProperties(name1,dtoPage);
            return setmealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);

        return R.success(dtoPage);
    }

    //删除套餐
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "套餐删除接口")
    public R<String> delete(@RequestParam List<Long> ids){
        //select count(*) from setmeal where id in (1,2,3) and status = 1
        setmealService.removeWithSetmeal(ids);
        redisTemplate.delete("setmeal_*");
        return R.success("套餐删除成功");
    }

    //起售/停售套餐
    @PostMapping("/status/{status}")
    public R<String> sale(@PathVariable String status,@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Setmeal> lqw = new LambdaUpdateWrapper<>();
        lqw.set(Setmeal::getStatus,status);
        lqw.in(Setmeal::getId,ids);
        setmealService.update(lqw);
        return R.success("操作成功");
    }

    //根据套餐id查询套餐数据
    @GetMapping("/{id}")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    @ApiOperation(value = "套餐条件查询接口")
    public R<SetmealDto> getSetmealId(@PathVariable Long id){
        System.out.println(id);
//        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(id != null,Setmeal::getId,id);
//        List<Setmeal> setmealList = setmealService.list(lqw);
//        LambdaQueryWrapper<SetmealDish> lqw2 = new LambdaQueryWrapper<>();
//        lqw2.eq(id != null,SetmealDish::getSetmealId,id);
//        List<SetmealDish> setmealDishList = setmealDishService.list(lqw2);
//        SetmealDto setmealDto = new SetmealDto();
//        BeanUtils.copyProperties(setmealList,setmealDto);
//        BeanUtils.copyProperties(setmealDishList,setmealDto);
        SetmealDto setmealDto = setmealService.getByIdWithSetmeal(id);
        return R.success(setmealDto);
    }

    //修改套餐
    @PutMapping
    public R<String> updateSetmeal(@RequestBody SetmealDto setmealDto){
        setmealService.updateWithSetmeal(setmealDto);
        redisTemplate.delete("setmeal_*");
        return R.success("修改套餐成功");
    }

    //根据套餐分类id查询该套餐分类下的套餐
    @GetMapping("/list")
    //@Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<Setmeal>> getSetMeal(String categoryId,String status){
        List<Setmeal> setmealList = (List<Setmeal>) redisTemplate.opsForValue().get("stemeal_"+categoryId+"_"+status);
        if(setmealList != null && setmealList.size()>0){
            return R.success(setmealList);
        }
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(categoryId != null,Setmeal::getCategoryId,categoryId);
        lqw.eq(status != null,Setmeal::getStatus,status);
        lqw.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmeals = setmealService.list(lqw);
        redisTemplate.opsForValue().set("stemeal_"+categoryId+"_"+status,setmeals,60, TimeUnit.MINUTES);
        return R.success(setmeals);
    }
}
